package org.bronycorps.mlptss.domain.ai;

import java.util.ArrayList;
import java.util.List;

import org.bronycorps.mlptss.domain.actor.AbstractActor;
import org.bronycorps.mlptss.domain.ai.actor.VirtualActor;
import org.bronycorps.mlptss.utils.VectorUtils;

import com.badlogic.gdx.math.Vector2;

public class PredictedStage {

	private final List<VirtualActor> actors = new ArrayList<VirtualActor>();

	private List<DatedPolygon> hitBoxes = null;

	private float snapshotTime = 0;

	public PredictedStage() {
	}

	public PredictedStage createSnapshot(float time) {
		PredictedStage snapshot = new PredictedStage();
		snapshot.snapshotTime = time;

		for (VirtualActor actor : this.actors) {
			snapshot.actors.add(actor.createSnapshot());
		}

		return snapshot;
	}

	private VirtualActor findActorBySource(AbstractActor source) {
		for (VirtualActor actor : this.actors) {
			if (actor.getSource().equals(source)) {
				return actor;
			}
		}
		return null;
	}

	public void generateCollisionBoxes(PredictedStage previousState) {
		this.hitBoxes = new ArrayList<DatedPolygon>();
		for (VirtualActor actor : this.actors) {
			VirtualActor previousActor = previousState.findActorBySource(actor
					.getSource());
			if (previousActor == null) {
				continue;
			}
			Vector2 base = new Vector2(actor.getPosition()).sub(previousActor
					.getPosition());
			final DatedPolygon box = VectorUtils.createOrientedTriangle(
					new Vector2(), base, actor.getSource().getHitBoxRadius());
			box.p0 = previousActor.getPosition();
			box.p1 = actor.getPosition();
			box.source = actor;

			box.setPosition(previousActor.getPosition().x,
					previousActor.getPosition().y);
			this.hitBoxes.add(box);
		}
	}

	public List<VirtualActor> getActors() {
		return this.actors;
	}

	public List<DatedPolygon> getHitBoxes() {
		return this.hitBoxes;
	}

	public float getSnapshotTime() {
		return this.snapshotTime;
	}

	public String positionsToString() {
		StringBuffer bf = new StringBuffer();
		for (VirtualActor a : this.actors) {
			bf.append(a.getPosition() + ",");
		}
		return bf.toString();
	}

	public void setSnapshotTime(float snapshotTime) {
		this.snapshotTime = snapshotTime;
	}

}